<script lang="ts" setup>
import { ref, reactive, computed } from "vue";
import { FormRules, FormInstance, ElMessageBox } from "element-plus";
import { RoleApi } from "@/Api";

interface Props {
   modelValue: boolean;
}

const props = withDefaults(defineProps<Props>(), {
   modelValue: false
});

const emit = defineEmits<{
   (e: "update:modelValue", value: boolean): void;
}>();

const dialogVisible = computed({
   get: () => props.modelValue,
   set: value => {
      if (!value) formRef.value?.resetFields();
      emit("update:modelValue", value);
   }
});
const loading = reactive({ add: false });
const disable = reactive({ add: false });
const formRef = ref<FormInstance>();

const form = reactive<Role.Create>({
   name: ""
});

const formRules = reactive<FormRules>({
   name: [{ required: true, message: "角色名称必填", trigger: "blur" }]
});

async function handlerAdd(formRef?: FormInstance) {
   if (!formRef) return;
   formRef.validate(async (valid, fields) => {
      if (!valid) return;
      try {
         const { code } = await RoleApi.Create(form);
         if (code === 200) {
            ElMessage.success("添加成功");
            dialogVisible.value = false;
         }
      } catch (error) {
         console.log("error", error);
      }
   });
}

/** 弹窗打开时 */
async function handlerOpen() {
   // await getRoleList();
}
</script>

<template>
   <el-dialog v-model="dialogVisible" ref="dialog" title="添加角色" width="500px" draggable append-to-body @open="handlerOpen">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="85">
         <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="数据角色名称" />
         </el-form-item>
      </el-form>
      <template #footer>
         <span class="dialog-footer">
            <el-button :loading="loading.add" :disabled="disable.add" type="primary" @click="handlerAdd(formRef)">
               添加
            </el-button>
         </span>
      </template>
   </el-dialog>
</template>

<style lang="scss" scoped>
.el-form {
   box-sizing: border-box;
   padding-inline: 20px;
}
.el-input {
   width: 100%;
}
</style>
